#include <iostream>
#include "ZhangsFingerRootsDetector.h"
#include "palmdll_yjy.h"

extern int g_SearchStart;
extern int palm_segment_e(const cv::Mat &img, cv::Mat &result);

ZhangsFingerRootsDetector::ZhangsFingerRootsDetector(cv::Mat &img)
{
    this->img = img;
}

ZhangsFingerRootsDetector::~ZhangsFingerRootsDetector()
{
}

int ZhangsFingerRootsDetector::palm_segment(const cv::Mat &img, cv::Mat &result, string &filename)
{

    return palm_segment_e(img, result, filename);
}

int ZhangsFingerRootsDetector::detect_fincon(cv::Mat &img, int result[6], string &filename)
{
    cv::Mat segment_result, img_gray;
    if(img.channels()>2) cv::cvtColor(img, img_gray, CV_BGR2GRAY);
    else img_gray=img;
    this->palm_segment(img, segment_result, filename);
    IplImage *imgInput = new IplImage(img_gray);
    IplImage *imgTh = new IplImage(segment_result);

    //-------------------------------------
    IplImage *imgPalm = cvCreateImage(cvSize(320, 240), 8, 1);   //标准手掌图像
    IplImage *imgBinary = cvCreateImage(cvSize(320, 240), 8, 1); //二值化手掌区域
    cvResize(imgInput, imgPalm);
    cvResize(imgTh, imgBinary);

    // debug
    // cvCircle(imgTh, cvPoint(result[0], result[1]), 5, cvScalar(0, 0, 255));
    // cvCircle(imgTh, cvPoint(result[4], result[5]), 5, cvScalar(0, 0, 255));
    // cvShowImage("imgTh", imgTh);
    // cvWaitKey(0);

    IplImage *imgPalmArea = myGetClearPalmArea(imgBinary); //最终的手掌区域
    IplImage *roi = cvCreateImage(cvSize(128, 128), 8, 1); //roi 图像

    uchar *palmData = (uchar *)imgPalm->imageData;   //获得手掌图像数据
    uchar *thData = (uchar *)imgPalmArea->imageData; //
    uchar *roiData = (uchar *)roi->imageData;        //

    int Sx[4], Sy[4]; //ROI坐标

    int ret = Lnpreprocessing(palmData, thData, roiData, Sx, Sy); //图像预处理

    if (!ret)
    {
        std::cout << "preprocessing error!" << std::endl;
        return 0;
    }

    //finger roots [x1,y1,x2,y2,x3,y3]
    result[0] = holeList[0][lastP1Index][0];
    result[1] = holeList[0][lastP1Index][1];
    result[2] = 0;
    result[3] = 0; //we don't care about middle-rings finger root
    result[4] = holeList[1][lastP2Index][0];
    result[5] = holeList[1][lastP2Index][1];

    const double scale_factor = img.cols / 320.0;
    for (int i = 0; i < 6; i++)
    {
        result[i] *= scale_factor;
    }

    delete imgInput;
    delete imgTh;
    return 1;
}

ObjectDetector *ZhangsFingerRootsDetector::detect(string &filename)
{
    int success = detect_fincon(this->img, this->fingerConner, filename);
    if (!success)
    {
        std::cout << "Zhang's method failed!" << std::endl;
    }
    return this;
}

int ZhangsFingerRootsDetector::getDetectedArr(int *result)
{
    if (fingerConner[0] == 0)
        return 0;

    for (int i = 0; i < 6; i++)
    {
        result[i] = this->fingerConner[i];
    }

    return 1;
}
